import { createStore } from 'vuex'

export default createStore({
  state: {
    books: [
      {
        id: 1,
        name: '岛上书店',
        autor: '加·译文',
        price: 28,
        count: 1
      },
      {
        id: 2,
        name: '边城',
        autor: '沈从文',
        price: 36,
        count: 1
      },
      {
        id: 3,
        name: '安娜卡列尼娜',
        autor: '列夫·托尔斯泰',
        price: 53,
        count: 1
      },
      {
        id: 4,
        name: '红楼梦',
        autor: '曹雪芹',
        price: 38,
        count: 1
      },
    ],
  },
  getters: {
    booksLength: state => {
      return state.books.length;
    },
    getTatalpirce: state => {
      let totalPrice = 0;
      for(let i in state.books){
          totalPrice += state.books[i].price * state.books[i].count;
      }
      return totalPrice;
    },
  },
  mutations: {
    increment: (state,payload) => {
      state.books[payload].count++;
    },
    decrement: (state,payload) => {
      state.books[payload].count--;
    },
    remove: (state,payload) => {
      state.books.splice(payload,1);
    }
  },
})
